package com.ctgu.chatapp.view.fragment.MainFragment.viewPager

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.ctgu.chatapp.databinding.FragmentFriendListByGroup
import com.ctgu.chatapp.model.Database.DataBaseManager
import com.ctgu.chatapp.view.adapter.FriendGroupAdapter
import com.ctgu.chatapp.viewModel.MainViewModel
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.Dispatchers.Main
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class FriendListByGroup : Fragment() {

    lateinit var binding: FragmentFriendListByGroup

    val viewModel by lazy { ViewModelProvider(requireActivity())[MainViewModel::class.java] }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentFriendListByGroup.inflate(inflater, container, false)
        binding.lifecycleOwner = requireActivity()
        initAdapter()
        return binding.root
    }

    private fun initAdapter() {
        val dataBase = DataBaseManager.getInstance(requireContext()).getFriendDao()
        val adapter =
            FriendGroupAdapter(
                mutableListOf(),
                requireContext(),
                viewModel.user.value!!.chatID.toInt(), viewModel.user.value!!.profile
            )
        val layout = LinearLayoutManager(requireContext())
        layout.orientation = LinearLayoutManager.VERTICAL
        binding.groupList.layoutManager = layout
        binding.groupList.adapter = adapter
        lifecycleScope.launch(IO) {
            viewModel.friendListByGroup.collect { it ->
                for (group in it) {
                    group.friendList =
                        dataBase.getGroupFriend(viewModel.user.value!!.chatID, group.type)
                }
                withContext(Main) {
                    adapter.changeData(it)
                }
            }
        }
    }

}
